package cn.wj.school.server.net.context;


import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.common.dto.BaseMsg;
import cn.wj.school.server.net.utils.ChannelUtils;
import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 链接的会话
 * @author kingston
 */
@Data
@Slf4j
public class IoSession {

	/** distributeKey auto generator  */
	private AtomicInteger dispatchKeyGenerator = new AtomicInteger();

	/** 网络连接channel */
	private Channel channel;

	private SyUserDTO user;

	/** ip地址 */
	private String ipAddr;

	private boolean reconnected;

	/** 业务分发索引 */
	private int dispatchKey;

	/** 拓展用，保存一些个人数据  */
	private Map<String, Object> attrs = new HashMap<>();



	public IoSession() {

	}

	public IoSession(Channel channel) {
		this.channel = channel;
		this.ipAddr = ChannelUtils.getIp(channel);
		this.dispatchKey = dispatchKeyGenerator.getAndIncrement();
	}


	/**
	 * 向客户端发送消息
	 * @param msg
	 */
	public void sendMsg(BaseMsg msg) {
		if (msg == null) {
			return;
		}
		if (channel != null) {
			channel.writeAndFlush(msg);
		}
	}

	public boolean isClose() {
		if (channel == null) {
			return true;
		}
		return !channel.isActive() ||
			   !channel.isOpen();
	}

	/**
	 * 关闭session
	 * @param reason {@link SessionCloseReason}
	 */
	public void close(SessionCloseReason reason) {
		try{
			if (this.channel == null) {
				return;
			}
			if (channel.isOpen()) {
				channel.close();
				log.info("close session[{}], reason is {}", this.user.getId(), reason);
			}else{
				log.info("session[{}] already close, reason is {}", this.user.getId(), reason);
			}
		}catch(Exception e){
		}
	}

}
